﻿using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Web.Mvc;
using ShopB2C.Entity;
using ShopB2C.Enums;
using ShopB2C.Helper;
using ShopB2C.ViewModels;

namespace ShopB2C.Controllers.Manager {
    /// <summary>
    /// 图片轮换
    /// </summary>
    public partial class ConfigController : BaseController {

        [OutputCache(Duration = 0, VaryByParam = "*")]
        public ActionResult ImageRepeat() {
            return View(new ImageRepeatViewModel() {
                Width = ConfigHelper.GetValue<int>(ConfigNodeNames.ImageRepeat, "width"),
                Height = ConfigHelper.GetValue<int>(ConfigNodeNames.ImageRepeat, "height"),
                Interval = ConfigHelper.GetValue<int>(ConfigNodeNames.ImageRepeat, "interval"),
                IsAutoPlay = ConfigHelper.GetValue(ConfigNodeNames.ImageRepeat, "isAutoPlay"),
                IsShowContent = ConfigHelper.GetValue(ConfigNodeNames.ImageRepeat, "isShowContent"),
                IsShowImgPage = ConfigHelper.GetValue(ConfigNodeNames.ImageRepeat, "isShowImgPage"),
                ImageRepeatList = _ir.GetImageRepeatList(string.Empty)
            });
        }

        [HttpPost]
        public ActionResult ImageRepeatConfigSave(ImageRepeatViewModel irv) {
            string msg = "保存配置操作成功完成!";
            try {
                ConfigHelper.SetValue<int>(ConfigNodeNames.ImageRepeat, "width", irv.Width);
                ConfigHelper.SetValue<int>(ConfigNodeNames.ImageRepeat, "height", irv.Height);
                ConfigHelper.SetValue<int>(ConfigNodeNames.ImageRepeat, "interval", irv.Interval);
                ConfigHelper.SetValue<string>(ConfigNodeNames.ImageRepeat, "isAutoPlay", irv.IsAutoPlay);
                ConfigHelper.SetValue<string>(ConfigNodeNames.ImageRepeat, "isShowContent", irv.IsShowContent);
                ConfigHelper.SetValue<string>(ConfigNodeNames.ImageRepeat, "isShowImgPage", irv.IsShowImgPage);
                ConfigHelper.Save();
            }
            catch {
                msg = "发生错误, 保存配置操作失败!";
            }
            return Content(msg, "text/plain");
        }

        [HttpPost]
        public ActionResult ImageRepeatEdit([DefaultValue(0)]int id) {
            List<ImageRepeatEntity> listImageRepeat = _ir.GetImageRepeatList(string.Empty);
            return View(new ImageRepeatViewModel() {
                ImageRepeat = id == 0 ? new ImageRepeatEntity() {
                    LinkUrl = "http://",
                    IsUse = true,
                    Sequence = listImageRepeat != null ? listImageRepeat.Count + 1 : 1,
                } : _ir.GetImageRepeatById(id)
            });
        }

        [HttpPost]
        public ContentResult ImageRepeatEditSave(ImageRepeatViewModel irv, FormCollection fc) {
            ImageRepeatEntity ire = irv.ImageRepeat;
            // 文件处理
            const int allowFileSize = 200;
            const int thumbWidth = 150;
            const int thumbHeight = 80;

            var file = Request.Files["fPhoto"];
            bool flag = true;

            if (file == null || file.ContentLength == 0) {
                if (ire.IId <= 0) {
                    return Content("未发现图片文件!", "text/plain");
                }
                flag = false;
            }

            if (flag) {
                if (file.ContentLength > allowFileSize * 1024) {
                    return Content("图片大小超过 200KB!", "text/plain");
                }

                string allowExt = ".gif,.bmp,.jpg,.png,";
                string ext = Path.GetExtension(file.FileName).ToLower();
                string oldName = Path.GetFileNameWithoutExtension(file.FileName);
                if (!allowExt.Contains(ext + ",")) {
                    return Content("图片类型只能是以 .gif,.bmp,.jpg,.png 结尾的文件!", "text/plain");
                }

                string fileName = string.Format("{0}{1}{2}",
                    RandomHelper.RandomString(8, RandomType.Letter),
                    oldName.Substring(0, oldName.Length >= 8 ? 8 : oldName.Length),
                    ext);
                string big = string.Format("{0}{1}", _irPath, fileName);
                string small = string.Format("{0}s_{1}", _irPath, fileName);
                file.SaveAs(big);

                MemoryStream ms = ThumbImageHelper.CuteThumbPhoto(thumbWidth, thumbHeight, big, true, true);
                using (FileStream fs = System.IO.File.Create(small)) {
                    fs.Write(ms.ToArray(), 0, (int)ms.Length);
                    fs.Flush();
                    fs.Close();
                }
                if (!string.IsNullOrEmpty(ire.Name)) {
                    System.IO.File.Delete(string.Format("{0}{1}", _irPath, ire.Name));
                    System.IO.File.Delete(string.Format("{0}s_{1}", _irPath, ire.Name));
                }
                ire.Name = fileName;
            }

            if (ire.IId == 0) {
                ire.IsUse = true;
                _ir.ImageRepeatAppend(ire);
            }
            else {
                _ir.ImageRepeatUpdate(ire);
            }

            return Content("成功完成操作!", "text/plain");
        }

        [HttpPost]
        public ActionResult ImageRepeatDelete(FormCollection fc) {
            List<ImageRepeatEntity> listImageRepeat = _ir.GetImageRepeatList(fc["cbKey"]);
            _ir.ImageRepeatDelete(fc["cbKey"]);
            // 删除图片文件
            foreach (ImageRepeatEntity ire in listImageRepeat) {
                if (!string.IsNullOrEmpty(ire.Name)) {
                    System.IO.File.Delete(string.Format("{0}{1}", _irPath, ire.Name));
                    System.IO.File.Delete(string.Format("{0}s_{1}", _irPath, ire.Name));
                }
            }

            return Content("成功完成删除多个操作!", "text/plain");
        }

        [HttpPost]
        public ContentResult ImageRepeatEditBatchSeq(FormCollection fc) {
            _ir.ImageRepeatBatchUpdateSequence(fc["cbKey"], fc["tbSequence"]);
            return Content("成功完成批量排序操作!", "text/plain");
        }

    }
}
